# from sqlalchemy.sql.functions import user
from flask import g, jsonify
from flask import request

from info import db
from info.models import News, Comment, CommentLike
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import news_blue
from flask import render_template


# 点赞
@news_blue.route("/comment_like", methods=["POST"])
@user_login_data
def comment_like():
    user = g.user

    if not user:
        return jsonify(errno=RET.SERVERERR, errmsg="请登陆")
    comment_id = request.json.get("comment_id")
    news_id = request.json.get("news_id")
    # 判断当前用户的动作，到底是想点赞还是取消点赞
    action = request.json.get("action")
    comment = Comment.query.get(comment_id)

    if action == "add":
        comment_like = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                CommentLike.user_id ==user.id).first()
        if not comment_like:
            comment_like = CommentLike()
            comment_like.comment_id = comment_id
            comment_like.user_id = user.id
            db.session.add(comment_like)
            comment.like_count += 1
    else:
        comment_like = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                CommentLike.user_id == user.id).first()
        if comment_like:
            db.session.delete(comment_like)
            comment.like_count -= 1

    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="点赞成功")


# 新闻评论
@news_blue.route("/news_comment", methods=["POST"])
@user_login_data
def news_comment():
    user = g.user
    if not user:
        return jsonify(errno=RET.SERVERERR, errmsg="请登录")
    news_id = request.json.get("news_id")
    comment_str = request.json.get("comment")
    parent_id = request.json.get("parent_id")

    # 用户评论
    new = News.query.get(news_id)
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = comment_str
    # 不是所有的评论都是神评论
    if parent_id:
        comment.parent_id = parent_id

    db.session.add(comment)
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="评论成功", data=comment.to_dict())


# 新闻收藏
@news_blue.route("/news_collect", methods=["GET", "POST"])
@user_login_data
def news_collect():
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    # 因为需要收藏新闻,肯定需要先把新闻查询出来才能收藏
    news = News.query.get(news_id)

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="没有这条新闻")
    user = g.user
    # 因为收藏新闻是用户行为,所以必须得判断当前用户是否已经登陆,只有登陆才可以收藏新闻
    if not user:
        return jsonify(errno=RET.SERVERERR, errmsg="请登录")
    if action == "collect":
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)

    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="收藏成功")


@news_blue.route("/<int:news_id>")
@user_login_data
def news_datail(news_id):
    user = g.user

    # user = user_login_data()
    # 右边热们新闻排行
    news_model = News.query.order_by(News.clicks.desc()).limit(9)
    news_list = []
    for news_dict in news_model:
        news_list.append(news_dict.to_dict())

    # 获取新闻详情
    news = News.query.get(news_id)

    # 收藏
    is_collected = False
    if user:
        if news in user.collection_news:
            is_collected = True

    # 新闻评论列表
    comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    comment_list = []
    comment_likes = []
    comment_like_ids = []
    if user:
        # 获取所有的点赞的评论
        comment_likes = CommentLike.query.filter(CommentLike.user_id == user.id).all()
        # 取出所有的点赞id
        comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]

    for comment in comments:
        # 取出评论的字典
        comment_dict = comment.to_dict()
        # 因为第一次进来,肯定所有的评论都没有点赞,所以默认值是false
        comment_dict["is_like"] = False
        if comment.id in comment_like_ids:
            comment_dict["is_like"] = True
        comment_list.append(comment_dict)

    data = {
        "user_info": user.to_dict() if user else None,
        "click_news_list": news_list,
        "news": news.to_dict(),
        "is_collected": is_collected,
        "comments": comment_list
    }
    return render_template("news/detail.html", data=data)
